package model

import (
	"context"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/monc"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var _ ChatModel = (*customChatModel)(nil)

type (
	// ChatModel is an interface to be customized, add more methods here,
	// and implement the added methods in customChatModel.
	ChatModel interface {
		chatModel
		FindManyByTimestamp(ctx context.Context, timestamp int64) ([]*Chat, error)
	}

	customChatModel struct {
		*defaultChatModel
	}
)

func (c *customChatModel) FindManyByTimestamp(ctx context.Context, timestamp int64) ([]*Chat, error) {
	data := make([]*Chat, 0)

	findOpts := options.Find()
	findOpts.SetLimit(300)
	findOpts.SetSort(bson.D{{"timestamp", 1}})

	err := c.conn.Find(ctx, &data, bson.D{{"timestamp", bson.D{{"$lte", timestamp}}}}, findOpts)

	switch err {
	case nil:
		return data, nil
	case monc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

// NewChatModel returns a model for the mongo.
func NewChatModel(url, db, collection string, c cache.CacheConf) ChatModel {
	conn := monc.MustNewModel(url, db, collection, c)
	return &customChatModel{
		defaultChatModel: newDefaultChatModel(conn),
	}
}
